// import { outLogin } from '@/services/ant-design-pro/api';
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Spin } from 'antd';
import { createStyles } from 'antd-style';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback,useEffect } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderSystemProps = {
  menu?: boolean;
  children?: React.ReactNode;
  systeminfo?: any,
};

// export const AvatarName = () => {
//   const { initialState } = useModel('@@initialState');
//   const { currentUser }:any = initialState || {};
//   return <span className="anticon">{currentUser?.name}</span>;
// };

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
  };
});

export const HeaderSystemSelect: React.FC<GlobalHeaderSystemProps> = ({ menu, children ,systeminfo}) => {
  const { styles } = useStyles();
  const { currentAppMenu,setCurrentAppMenu, clearCurrentTabList } = useModel('global');
  const { initialState, setInitialState }:any = useModel('@@initialState');
  const { fetchUserInfo } = initialState;

  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    // await outLogin();
    // const { search, pathname } = window.location;
    // const urlParams = new URL(window.location.href).searchParams;
    // /** 此方法会跳转到 redirect 参数所在的位置 */
    // const redirect = urlParams.get('redirect');
    // // Note: There may be security issues, please note
    // if (window.location.pathname !== '/user/login' && !redirect) {
    //   history.replace({
    //     pathname: '/user/login',
    //     search: stringify({
    //       redirect: pathname + search,
    //     }),
    //   });
    // }
    history.replace('/login');
  };


  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if(systeminfo.id == key) return;
      const _fsystem = fetchUserInfo.find((_item:any) => _item.id == key);
      // console.log('====onMenuClick===',key,_fsystem,systeminfo);
      // setInitialState((s:any) => ({ ...s, currentSystem: _fsystem }));
      clearCurrentTabList();
      setTimeout(()=>{
        history.push('/'+_fsystem.name+'/home');
      });
      // window.location.reload();
    },
    [currentAppMenu],
  );

  const loading = (
    <span className={styles.action}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  if (!systeminfo || !systeminfo.systemname) {
    return loading;
  }
  if (!fetchUserInfo.length) {
    return loading;
  }
  
  useEffect(() => {
    // console.log('====systeminfo===',systeminfo,currentAppMenu);
    if(systeminfo?.id != currentAppMenu?.id ||!currentAppMenu?.id){
      setCurrentAppMenu(systeminfo);
    }
  }, [systeminfo]);

 
 
  // const menuItems = [
  //   {
  //     key: 'logout',
  //     icon: <LogoutOutlined />,
  //     label: '退出登录',
  //   },
  // ];
  const menuItems:any = [];
  fetchUserInfo.map((_item: any)=>{
    menuItems.push({
      key: _item.id,
      // icon: <LogoutOutlined />,
      label: _item.systemname,
    })
  });
  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      {children}
    </HeaderDropdown>
  );
};